/*
 * @Author: GM 
 * @Date: 2017-03-25 14:53:11 
 * @Last Modified by: GM
 * @Last Modified time: 2017-03-25 14:53:52
 */
/**
 * 会员店商品新增和编辑公用JS文件
 */


/**
 * [skuAdd sku属性组合列表添加内容]
 * @param  {objerc} dom       操作dom对象
 * @param  {array} attribute 商品属性分类数组
 * @param  {array} skuAttr  后台传回历史参数记录
 * @param  {number} type      状态 1 新增, 2编辑
 */
function skuAdd(dom, attribute, skuAttr, type) {
    var joinStr = jointStr(attribute);

    attrIdStr = joinStr.attrIdStr;
    attrNameStr = joinStr.attrNameStr;

    $('#attribute-list').empty();
    var oldSkuAttr = skuAttr; //历史选择
    var oldSkuAttrValue = [];

    for (var i = 0; i < attrIdStr.length; i++) {
        var id = i + 1;
        var imgSrc1 = "";
        var imgSrc2 = "";
        var inventory = ""; //sku组合库存
        var price = ""; //价格
        var wholesale = "--"; //建议零售价
        var shop_sku_sn = ''; //商品编码
        var editTypeStr = ""; //列表勾选

        var _attrIdStr = attrIdStr[i].length == 0 ? attrIdStr[i] : attrIdStr[i].split('|').sort().join("|"); //当前组合属性id组合

        for (var k = 0; k < oldSkuAttr.length; k++) {
            if (oldSkuAttr[k].attr_str.split('|').sort().join("|") === _attrIdStr) {
                imgSrc1 = oldSkuAttr[k].sku_img;
                imgSrc2 = oldSkuAttr[k].sku_img2;
                price = oldSkuAttr[k].m_goods_price ? oldSkuAttr[k].m_goods_price : "";
                shop_sku_sn = oldSkuAttr[k].shop_sku_sn ? oldSkuAttr[k].shop_sku_sn : '';
                inventory = oldSkuAttr[k].inventory ? oldSkuAttr[k].inventory : "";
                wholesale = oldSkuAttr[k].wholesale_retail_price ? '￥'+oldSkuAttr[k].wholesale_retail_price : "--";
            }
        }

        //新增
        if (type === 1) {
            editTypeStr =
                '       <span class="scheckbox form-input" title="' + attrNameStr[i] + '">' +
                '           <i></i>' +
                '           <input type="checkbox" class="shide" name="attr_str[]" value="' + attrIdStr[i] + '" data-description="' + attrNameStr[i] + '">' + attrNameStr[i] +
                '       </span>';
        }
        //编辑
        else if (type === 2) {
            editTypeStr =
                '       <span class="scheckbox form-input" title="' + attrNameStr[i] + '">' +
                '           <i></i>' +
                '           <input type="hidden" name="sku_id[]" data-selector="sku-id" value=""/>' +
                '           <input type="checkbox" class="shide" name="attr_str[]" value="' + attrIdStr[i] + '" data-description="' + attrNameStr[i] + '">' + attrNameStr[i] +
                '       </span>';
        }

        var upload = '<a href="javascript:;" class="img-upload">' +
            '    <i class="round-delete"></i>' +
            '    <input type="file" name="file" accept="image/jpg,image/jpeg,image/gif,image/png" id="sku-uploadimage-file' + id + '" class="uploadimage-file  hide" onchange="uploadImg(this, 2)"/>' +
            '    <input type="hidden" name="sku_img[]" class="js-attr-upload" value="' + imgSrc1 + '" disabled>' +
            '    <div id="sku-uploadimage-loading' + id + '" class="hide">Uploading...</div>' +
            '    <div id="sku-uploadimage-preview' + id + '" class="uploadimage-preview" onclick="document.querySelector(\'#sku-uploadimage-file' + id + '\').click()">' +
            '       <img id="sku-uploadimage-img' + id + '" src="' + imgSrc2 + '">' +
            '    </div>' +
            '    <p>上传图片</p>' +
            '</a>';

        dom.append(
            '<tr>' +
            '    <td class="sku-list-title">' +
            editTypeStr +
            '    </td>' +
            '    <td>' +
            '        <input type="text" class="form-control input-sm js-attr-input-sn" value="' + shop_sku_sn + '" name="goods_sn[]" maxlength="20" disabled>' +
            '    </td>' +
            '    <td>' +
            '        <input type="text" class="js-attr-input-price" name="goods_cost[]" placeholder="一口价" value="' + price + '" maxlength="11" disabled>' +
            '    </td>' +
            '    <td>'+
            '        <p class="js-attr-wholesale">'+ wholesale +'</p>' +
            '    </td>'+

            '    <td>' + '<input type="text" class="js-attr-input-inventory" name="inventory[]" placeholder="库存量" value="' + inventory + '" maxlength="6" disabled>' + '</td>' +
            '    <td>' +
            '        <div class="attr-upload-img">' +
            upload +
            '        </div>' +
            '    </td>' +
            '</tr>');
    }

    var newSkuAttr = $('#attribute-list .scheckbox input[type=checkbox]'); //已有属性sku组合 dom
    var newSkuAttrValue = []; //sku属性组合列表
    //输出新SKU 组合数组
    for (var i = 0; i < newSkuAttr.length; i++) {
        var _arr = $(newSkuAttr[i]).val().split("|");
        _arr = _arr.sort();
        newSkuAttrValue.push(_arr);
    }
    for (var i = 0; i < oldSkuAttr.length; i++) {
        oldSkuAttrValue.push(oldSkuAttr[i].attr_name);
    }
    editAttrAdd(newSkuAttrValue, oldSkuAttrValue, newSkuAttr, skuAttr);

    return { attrIdStr: attrIdStr, attrNameStr: attrNameStr };
}


/**
 * [editAttrAdd description]
 * @param  {array} arr1    新sku组合数组
 * @param  {array} arr2    旧sku组合数组
 * @param  {object} attrDom sku DOM对象
 * @param  {array} skuAttr 后台传回历史参数记录
 */
function editAttrAdd(arr1, arr2, attrDom, skuAttr) {
    if (arr1.length > arr2.length) {
        var _arr = [];
        for (var i = 0; i < arr2.length; i++) {
            for (var k = 0; k < arr1.length; k++) {
                if (arr1[k].sort().toString() === arr2[i].sort().toString()) {
                    if (_arr.length !== 0) {
                        if (_arr.indexOf(arr2[i]) === -1) {
                            _arr.push({ id: k, val: arr2[i] });
                        }
                    } else {
                        _arr.push({ id: k, val: arr2[i] });
                    }
                } else {
                    attrDom.eq(k).siblings('input[type=hidden]').val('-1');
                    attrDom.eq(k).prop('checked', false);
                    attrDom.eq(i).parent().removeClass('active');
                    attrDom.eq(k).parents('tr').find('input[type=text]').prop('disabled', true).val("");
                    attrDom.eq(k).parents('tr').find('.js-attr-upload').prop('disabled', true);

                }
            }
        }

        for (var i = 0; i < _arr.length; i++) {
            for (var k = 0; k < skuAttr.length; k++) {
                if (skuAttr[k].attr_str.split('|').sort().join("|") == _arr[i].val.join("|")) {
                    attrDom.eq(_arr[i].id).prop('checked', true);
                    attrDom.eq(_arr[i].id).parent().addClass('active');
                    attrDom.eq(_arr[i].id).siblings('input[type=hidden]').val(skuAttr[k].sku_id);
                    attrDom.eq(_arr[i].id).parents('tr').find('input[type=text]').prop('disabled', false);
                    attrDom.eq(_arr[i].id).parents('tr').find('.js-attr-upload').prop('disabled', false);

                    attrDom.eq(_arr[i].id).parents('tr').find('.js-attr-input-sn').val(skuAttr[k].shop_sku_sn);
                    attrDom.eq(_arr[i].id).parents('tr').find('.js-attr-input-inventory').val(skuAttr[k].inventory);
                    attrDom.eq(_arr[i].id).parents('tr').find('.js-attr-input-price').val(skuAttr[k].m_goods_price);
                    attrDom.eq(_arr[i].id).parents('tr').find('.js-attr-wholesale').val('￥'+skuAttr[k].wholesale_retail_price);

                }
            }
        }
    }

    if (arr1.length < arr2.length) {

        var _arr = [];
        for (var i = 0; i < arr1.length; i++) {
            for (var k = 0; k < arr2.length; k++) {
                if (arr1[i].sort().toString() === arr2[k].sort().toString()) {
                    if (_arr.length !== 0) {
                        if (_arr.indexOf(arr1[i]) === -1) {
                            _arr.push({ id: i, val: arr1[i] });
                        }
                    } else {
                        _arr.push({ id: i, val: arr1[i] });
                    }
                } else {
                    attrDom.eq(k).siblings('input[type=hidden]').val('-1');
                    attrDom.eq(k).prop('checked', false);
                    attrDom.eq(i).parent().removeClass('active');
                    attrDom.eq(k).parents('tr').find('input[type=text]').prop('disabled', true).val("");
                    attrDom.eq(k).parents('tr').find('.js-attr-upload').prop('disabled', true);

                }
            }
        }

        for (var i = 0; i < skuAttr.length; i++) {
            for (var k = 0; k < _arr.length; k++) {
                if (skuAttr[i].attr_str.split('|').sort().join("|") == _arr[k].val.join("|")) {
                    attrDom.eq(_arr[k].id).prop('checked', true);
                    attrDom.eq(_arr[k].id).parent().addClass('active');
                    attrDom.eq(_arr[k].id).siblings('input[type=hidden]').val(skuAttr[i].sku_id);
                    attrDom.eq(_arr[k].id).parents('tr').find('input[type=text]').prop('disabled', false);
                    attrDom.eq(_arr[k].id).parents('tr').find('.js-attr-upload').prop('disabled', false);

                    attrDom.eq(_arr[k].id).parents('tr').find('.js-attr-input-sn').val(skuAttr[i].shop_sku_sn);
                    attrDom.eq(_arr[k].id).parents('tr').find('.js-attr-input-inventory').val(skuAttr[i].inventory);
                    attrDom.eq(_arr[k].id).parents('tr').find('.js-attr-input-price').val(skuAttr[i].m_goods_price);
                    attrDom.eq(_arr[k].id).parents('tr').find('.js-attr-wholesale').val('￥'+skuAttr[i].wholesale_retail_price);
                }
            }
        }
    }

    if (arr1.length === arr2.length) {
        var _arr = [];
        for (var i = 0; i < arr1.length; i++) {
            for (var k = 0; k < arr2.length; k++) {
                if (arr1[i].sort().toString() === arr2[k].sort().toString()) {
                    if (_arr.length !== 0) {
                        if (_arr.indexOf(arr1[i]) === -1) {
                            _arr.push({ id: i, val: arr1[i] });
                        }
                    } else {
                        _arr.push({ id: i, val: arr1[i] });
                    }
                } else {
                    attrDom.eq(k).siblings('input[type=hidden]').val('-1');
                    attrDom.eq(k).prop('checked', false);
                    attrDom.eq(i).parent().removeClass('active');
                    attrDom.eq(k).parents('tr').find('input[type=text]').prop('disabled', true).val("");
                    attrDom.eq(k).parents('tr').find('.js-attr-upload').prop('disabled', true);

                }
            }
        }

        for (var i = 0; i < skuAttr.length; i++) {
            for (var k = 0; k < _arr.length; k++) {
                if (skuAttr[i].attr_str.split('|').sort().join("|") == _arr[k].val.join("|")) {
                    attrDom.eq(_arr[k].id).prop('checked', true);
                    attrDom.eq(_arr[k].id).parent().addClass('active');
                    attrDom.eq(_arr[k].id).siblings('input[type=hidden]').val(skuAttr[i].sku_id);
                    attrDom.eq(_arr[k].id).parents('tr').find('input[type=text]').prop('disabled', false);
                    attrDom.eq(_arr[k].id).parents('tr').find('.js-attr-upload').prop('disabled', false);

                    attrDom.eq(_arr[k].id).parents('tr').find('.js-attr-input-sn').val(skuAttr[i].shop_sku_sn);
                    attrDom.eq(_arr[k].id).parents('tr').find('.js-attr-input-inventory').val(skuAttr[i].inventory);
                    attrDom.eq(_arr[k].id).parents('tr').find('.js-attr-input-price').val(skuAttr[i].m_goods_price);
                    attrDom.eq(_arr[k].id).parents('tr').find('.js-attr-wholesale').val('￥'+skuAttr[i].wholesale_retail_price);
                }
            }
        }
    }
}


//存储属性组合列表
/**
 * [saveListAttr description]
 * @param  {object} dom      操作DOM
 * @param  {array} SKU_JSON 后台传回历史参数记录
 * @param  {array} skuAttr  自存历史参数记录
 * @return {object}         SKU_JSON, skuAttr
 */
var saveListAttr = function(dom, SKU_JSON, skuAttr) {
    var parentDom = dom;
    var id = parentDom.index();
    var _SKU_JSON = SKU_JSON
    var _skuAttr = skuAttr;
    var _activeAttrId = []; //已选元素id

    var _sku_json = function(_SKU_JSON) {
        var _arr = [];
        var _sku = SKU_JSON;

        for (var i = 0; i < _sku.length; i++) {
            _arr.push({
                id: i,
                sku_id: _sku[i].sku_id,
                attr_name: _sku[i].attr_name,
                attr_str: _sku[i].attr_str,
                attr_name_val: _sku[i].attr_name_val,
                shop_sku_sn: _sku[i].shop_sku_sn,
                m_goods_price: _sku[i].m_goods_price,
                wholesale_retail_price: _sku[i].wholesale_retail_price,
                inventory: _sku[i].inventory,
                sku_img: _sku[i].sku_img,
                sku_img2: _sku[i].sku_img2,

            });

            _activeAttrId.push(_sku[i].attr_name.sort(sortNumber).toString());
        }

        return _arr;
    }();

    var attr_str = parentDom.find('input[type=checkbox]').val();
    var attr_name_val = ("" + parentDom.find('input[type=checkbox]').data("description")).split(" | ").join("|");
    var shop_sku_sn = parentDom.find('.js-attr-input-sn').val();

    var m_goods_price = parentDom.find('.js-attr-input-price').val();
    var inventory = +parentDom.find('.js-attr-input-inventory').val();
    var wholesale_retail_price = +parentDom.find('.js-attr-wholesale').val();
    var sku_img = parentDom.find('.js-attr-upload').val();
    var sku_img2 = parentDom.find('.uploadimage-preview img').attr('src');
    var attr_name = ("" + parentDom.find('input[type=checkbox]').val()).split("|").sort();

    var _data = {
        id: id,
        attr_name: attr_name,
        attr_str: attr_str,
        attr_name_val: attr_name_val,
        shop_sku_sn: shop_sku_sn,
        m_goods_price: m_goods_price,
        inventory: inventory,
        sku_img: sku_img,
        sku_img2: sku_img2
    };

    // 排序函数
    function sortNumber(a, b) {
        return a - b;
    }

    if (_skuAttr.length === 0) {
        if (_data.id !== -1 && attr_str !== undefined && shop_sku_sn !== undefined && sku_img !== undefined && sku_img2 !== undefined) {
            if ($.inArray(_data.attr_name.sort(sortNumber).toString(), _activeAttrId) === -1) {
                _skuAttr.push(_data);
            }
        }
    } else {
        var _arr = _skuAttr;
        var _arrLen = _arr.length

        for (var i = 0; i < _arrLen; i++) {
            if (id == _arr[i].id) {
                _arr.splice(i, 1, _data);

            } else {
                if (_data.id !== -1 && attr_str !== undefined && shop_sku_sn !== undefined && sku_img !== undefined && sku_img2 !== undefined) {
                    _arr.push(_data);
                }
            }
        }
        _skuAttr = _arr;
    }

    var skuLen = _sku_json.length; //历史数据
    var skuAttrLen = skuAttr.length; //新数据
    var hasPos = []; //存储重复pos 位置
    var _skuAllAttr = _skuAttr.concat(_sku_json); //合成后参数
    var _skuAllLen = _skuAllAttr.length;
    var _skuId = []; //数据ID
    var _outStr = []; //去重后数据

    for (var i = 0; i < _skuAllLen; i++) {
        var _str = _skuAllAttr[i].attr_name.sort(sortNumber).toString();
        if ($.inArray(_str, _skuId) === -1) {
            _skuId.push(_str);
        }
    }
    $.each(_skuId, function(i, el) {
        if ($.inArray(el, _outStr) === -1) {
            _outStr.push(_skuAllAttr[i]);
        }
        // else {
        //  _skuAllAttr.splice(i, 1);
        // }
    });

    return { "skuAttr": _outStr }
}

//表单验证
$().ready(function() {
    $("#goods-form").validate({
        rules: {
            goods_name: {
                required: true
            },
            sale_point: {
                required: true
            },
            brand_id: {
                required: true
            },
            volume: {
                required: true,
                number: true,
                min: 0.0001
            },
            weight: {
                required: true,
                number: true,
                min: 0.0001
            }

        },
        messages: {
            goods_name: {
                required: '请输入商品名称'
            },
            sale_point: {
                required: '请输入商品卖点'
            },
            brand_id: {
                required: '请选择商品品牌'
            },
            volume: {
                required: '请输入单个商品体积',
                number: '参数只能为数字',
                min: '体积不能少于0.0001'
            },
            weight: {
                required: '请输入单个商品重量',
                number: '参数只能为数字',
                min: '重量不能少于0.0001'
            }
        },
        errorElement: "div",
        errorPlacement: function(error, element) {
            $(element)
                .parent()
                .append(error);
        }
    });
});